<template>
  <div>
    <p v-if="res" style="color:red;">审核未通过：{{res}}</p>
    <a-form :form="form" @submit="handleSubmit" style="width:60%;margin:0px auto;">
      <!-- <div>设置登录密码</div> -->
      <a-row>
        <a-col :xs="{ span : 24 }" :sm="{ span:9 }" class="formGroupTitle">基本信息</a-col>
      </a-row>
      <a-form-item v-bind="formItemLayout" label="性别">
        <a-radio-group
          :disabled="btnlimits"
          name="title"
          v-decorator="[
                        'sex',
                        {
                            rules: [{
                            required: true, message: '请选择性别',
                            }],
                        }
                        ]"
        >
          <a-radio :value="1">男</a-radio>
          <a-radio :value="2">女</a-radio>
        </a-radio-group>
      </a-form-item>
      <a-form-item v-bind="formItemLayout" label="职业">
        <div>
          <a-select
            :disabled="btnlimits"
            labelInValue
            placeholder="请选择职业"
            class="width-sty"
            @change="handleVocationChange"
            v-decorator="[
                        'vocation',
                        {
                            
                            rules: [{
                            required: true, message: '请选择职业',
                            }],
                        }
                        ]"
          >
            <a-select-option value="type1">党政机关人员</a-select-option>
            <a-select-option value="type2">企事业单位工作人员</a-select-option>
            <a-select-option value="type3">商业及服务业工作人员</a-select-option>
            <a-select-option value="type4">农林牧渔劳动者</a-select-option>
            <a-select-option value="type5">学生</a-select-option>
            <a-select-option value="type6">军人</a-select-option>
            <a-select-option value="type7">无业</a-select-option>
            <a-select-option value="type8">其他</a-select-option>
          </a-select>
        </div>
      </a-form-item>
      <a-form-item v-bind="formItemLayout" label="Email">
        <a-input
          :disabled="btnlimits"
          class="width-sty"
          placeholder="请输入Email"
          v-decorator="[
                        'email', { rules: [{type: 'email', message: '请输入有效邮箱地址!'}]}
                        ]"
        />
      </a-form-item>

      <a-form-item v-bind="formItemLayout" label="联系地址">
        <a-cascader
          :disabled="btnlimits"
          v-decorator="[
                      'pcd'
                    ]"
          class="width-sty"
          labelInValue
          :options="options"
          @change="onChange"
          placeholder="请选择联系地址"
        />
      </a-form-item>

      <a-form-item v-bind="formItemLayout" label="详细地址">
        <a-textarea
          :disabled="btnlimits"
          class="width-sty"
          v-decorator="[
                      'realAddress'
                    ]"
          placeholder="请输入详细地址"
          :rows="2"
        />
      </a-form-item>

      <a-row>
        <a-col :xs="{ span : 24 }" :sm="{ span:9 }" class="formGroupTitle">实名认证</a-col>
      </a-row>
      <a-form-item v-bind="formItemLayout" label="姓名">
        <a-input
          :disabled="btnlimits"
          class="width-sty"
          placeholder="请输入本人姓名"
          v-decorator="[
                    'name',
                    {
                        rules: [{
                        required: true, message: '请输入姓名',
                        }],
                    }
                    ]"
        />
      </a-form-item>

      <a-form-item v-bind="formItemLayout" label="证件类型">
        <div>
          <a-select
            v-decorator="[
                    'Idtype',
                    {
                        rules: [{
                        required: true, message: '请选择证件类型',
                        }],initialValue:'jack'
                    }
                    ]"
            class="width-sty"
            disabled
          >
            <a-select-option value="jack">身份证</a-select-option>
            <a-select-option value="jack2">护照</a-select-option>
            <a-select-option value="jack3">港澳台通行证</a-select-option>
            <a-select-option value="jack4">军官证</a-select-option>
            <a-select-option value="jack5">户口簿</a-select-option>
          </a-select>
        </div>
      </a-form-item>

      <a-form-item v-bind="formItemLayout" label="证件号码">
        <a-input
          :disabled="btnlimits"
          class="width-sty"
          placeholder="请输入本人证件号码"
          v-decorator="[
                    'idNo',
                    {
                        rules: [{
                        required: true, message: '请输入证件号码',
                        },{
                         validator: validateIdentityNo
                       }],validateTrigger: 'blur'
                    }
                    ]"
        />
      </a-form-item>

      <a-form-item v-bind="formItemLayout" label="证件有效期">
        <a-date-picker
          placeholder="请选择证件有效期"
          @change="dateChange"
          v-decorator="[
                      'expiryDate',
                      {rules: [{ required: true, message: '请选择证件有效期' }]}
                    ]"
        />
      </a-form-item>

      <a-form-item
        v-bind="formItemLayout"
        label="上传证件"
        :help="`支持图片格式JPG、PNG，且每个文件大小不超过${imageSize}M`"
      >
        <div class="clearfix" style="display:inline-block;">
          <a-upload
            v-decorator="['avatar2', {
                                rules: [{
                                required: true, message: '请输入身份证正/反面',
                                }],
                            }]"
            :data="{to}"
            name="upfile"
            :headers="henderstoken"
            action="/file/file/upload"
            listType="picture-card"
            :fileList="fileList"
            @preview="handlePreview"
            @change="handleChange"
          >
            <div v-if="fileList.length < 1">
              <a-icon type="plus" />
              <div class="ant-upload-text">人像面</div>
            </div>
          </a-upload>
          <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
            <img alt="example" style="width: 100%" :src="previewImage" />
          </a-modal>
        </div>
        <div class="clearfix" style="display:inline-block;">
          <a-upload
            :data="{to}"
            name="upfile"
            :headers="henderstoken"
            action="/file/file/upload"
            listType="picture-card"
            :fileList="fileList2"
            @preview="handlePreview2"
            @change="handleChange2"
          >
            <div v-if="fileList2.length < 1">
              <a-icon type="plus" />
              <div class="ant-upload-text">国徽面</div>
            </div>
          </a-upload>
          <a-modal :visible="previewVisible2" :footer="null" @cancel="handleCancel2">
            <img alt="example" style="width: 100%" :src="previewImage2" />
          </a-modal>
        </div>
      </a-form-item>
      <!-- <a-row>
        <a-col :xs="{ span : 24 }" :sm="{ span:14,offset:10 }">
          <a-form-item>
            <a-checkbox @change="handleCheckChange">本人充分了解并清楚知晓出租、出借、出售、购买账户的相关法律责任和惩戒措施，承诺依法依规开立和使用本人账户</a-checkbox>
          </a-form-item>
        </a-col>
      </a-row>-->

      <a-row>
        <a-col :xs="{ span : 24 }" :sm="{ span:14,offset:10 }">
          <!-- <a-button class="btn-class submitButton" type="primary" v-if="!issee" disabled>下一步</a-button> -->
          <a-button class="submitButton" type="primary" html-type="submit" :loading="loading">下一步</a-button>
        </a-col>
      </a-row>
    </a-form>
    <div></div>
  </div>
</template>
<script>
import {
  Radio,
  Input,
  InputNumber,
  DatePicker,
  Cascader,
} from "ant-design-vue";
import api from "@/common/api";
import moment from "moment";
import { mapState } from "vuex";
function getBase64(img, callback) {
  const reader = new FileReader();
  reader.addEventListener("load", () => callback(reader.result));
  reader.readAsDataURL(img);
}
export default {
  data() {
    return {
      henderstoken: {
        Authorization: localStorage.getItem("token"),
      },
      to:sessionStorage.getItem("memberNo") + "_" + sessionStorage.getItem("username"),
      form: this.$form.createForm(this),
      text: [],
      res: "",
      id: "",
      personid: "",
      memberNo: "",
      mod: "",
      previewVisible: false,
      previewVisible2: false,
      previewImage: "",
      previewImage2: "",
      fileList: [],
      fileList2: [],
      picdata: "",
      loading: false,
      imageUrl1: "",
      imageUrl2: "",
      checkNick: false,
      issee: false,
      province: {},
      email: "",
      sex: "",
      vocation: {},
      city: {},
      address: "",
      district: {},
      name: "",
      idNo: "",
      expiryDate: "",
      btnlimits: false,
      // options: [],
      options: [],
      imgHead: "",
      imgEmblem: "",
      formItemLayout: {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 9 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 12, offset: 1 },
          md: { span: 10, offset: 1 },
        },
      },
      formItemTailLayout: {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 7 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 12, offset: 7 },
          md: { span: 10, offset: 7 },
        },
      },
    };
  },
  computed: {
    ...mapState({
      imageSize: (state) => state.imageSize,
    }),
  },
  created() {
    if (this.$route.query.modify) {
      console.log("修改");
      this.btnlimits = true;
      this.getPerdata();
    } else {
      this.btnlimits = false;
      console.log("222");
    }
  },
  mounted: function () {
    this.getareaData();
    this.memberNo = sessionStorage.getItem("memberNo");
  },
  methods: {
    moment,
    validatemail(rule, value, callback) {
      const reg = new RegExp(
        "^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$"
      );
      if (value && !reg.test(value)) {
        callback("您输入的邮箱格式有误！");
        return;
      } else {
        this.email = value;
        console.log(this.email);
        callback();
      }
    },
    getareaData() {
      this.$axios.get("/agent/division/all").then((res) => {
        console.log("res", res);
        const result = res.data;
        if (res.data.list) {
          let list = result.list;
          let arr = [];
          let newArr = list.map((item, index, list) => {
            let test = {
              label: item.label,
              value: item.value,
              children: [],
            };
            arr.push(test);
            if (item.children) {
              let children = [];

              for (let i = 0; i < item.children.length; i++) {
                let test2 = {
                  label: item.children[i].label,
                  value: item.children[i].value,
                  children: [],
                };
                children.push(test2);

                if (item.children[i].children) {
                  let child2 = [];
                  for (let a = 0; a < item.children[i].children.length; a++) {
                    let test3 = {
                      label: item.children[i].children[a].label,
                      value: item.children[i].children[a].value,
                    };
                    child2.push(test3);
                  }
                  children[i].children = child2;
                }
              }
              arr[index]["children"] = children;
            }
            return arr;
          });
          this.options = newArr[0];
         
        } else {
          console.log("res", res);
        }
      });
    },
    getPerdata() {
      this.$axios.get("/agent/customer/getData").then((res) => {
        console.log("res", res);
        if (res.data.code == "OK") {
          let data = res.data.data;
          this.vocation = data.logCustomerResponse.vocationItem;
          this.province = data.logCustomerResponse.provinceItem;
          this.city = data.logCustomerResponse.cityItem;
          this.district = data.logCustomerResponse.districtItem;
          this.res = data.logCustomerResponse.remark;
          // console.log("pcd:", [
          //   data.logCustomerResponse.provinceItem.value,
          //   data.logCustomerResponse.cityItem.value,
          //   data.logCustomerResponse.districtItem.value
          // ]);
          this.id = data.logCustomerResponse.id;
          this.personid = data.logIdentityAddResponse.id;
          this.form.setFieldsValue({
            sex: data.logCustomerResponse.sex,
            vocation: this.vocation,
            realAddress: data.logCustomerResponse.address,
            pcd: [
              data.logCustomerResponse.provinceItem.value,
              data.logCustomerResponse.cityItem.value,
              data.logCustomerResponse.districtItem.value,
            ],
            email: data.logCustomerResponse.email,
            name: data.logIdentityAddResponse.identityName,
            expiryDate: moment(data.logIdentityAddResponse.expiryDate),
            idNo: data.logIdentityAddResponse.identityNo,
          });
          this.expiryDate = data.logIdentityAddResponse.expiryDate;
          // 身份证前面照
          this.fileList = [
            {
              uid: "-1",
              name: "xxx.png",
              status: "done",
              url: "/file/file/download/" + data.logIdentityAddResponse.imgHead,
            },
          ];
          this.imgHead = data.logIdentityAddResponse.imgHead;
          let imgHead = {
            imgHead: data.logIdentityAddResponse.imgHead,
          };
          api.setOrgPicData(
            imgHead,
            (res) => {
              if (res.code == "OK") {
                console.log("res", res);
                console.log("身份证前面上传成功");
                this.form.setFieldsValue({
                  avatar2: data.logIdentityAddResponse.imgHead,
                });
              } else {
                console.log(res);
              }
            },
            (err) => {}
          );
          // 身份证反面照
          this.fileList2 = [
            {
              uid: "-11",
              name: "xxx.png",
              status: "done",
              url:
                "/file/file/download/" + data.logIdentityAddResponse.imgEmblem,
            },
          ];
          this.imgEmblem = data.logIdentityAddResponse.imgEmblem;
          let imgEmblem = {
            imgEmblem: data.logIdentityAddResponse.imgEmblem,
          };
          api.setOrgPicData(
            imgEmblem,
            (res) => {
              if (res.code == "OK") {
                console.log("res", res);
                console.log("身份证前面上传成功");
                // this.form.setFieldsValue({
                //   avatar2: this.imgList.imgHead
                // });
              } else {
                console.log(res);
              }
            },
            (err) => {}
          );
        } else {
          console.log("res", res);
        }
      });
    },
    doNext(step) {
      console.log(step);
      var st = step + 1;
      this.$router.push("/PersonRegister/step" + st);
    },
    validateIdentityNo(rule, value, callback) {
      const form = this.form;
      if (value && !/(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(value)) {
        callback("您输入的身份证号码格式有误！");
      } else {
        console.log("身份证号码！", value);
        this.AdultorNot(value, callback);
      }
      callback();
    },
    handleCheckChange(e) {
      console.log("changevalue2", e.target.checked);
      if (e.target.checked == true) {
        this.issee = true;
      } else {
        this.issee = false;
      }
    },
    dateChange(date, dateString) {
      console.log("dateString", dateString);
      this.expiryDate = dateString;
    },
    onChange(value, selectedOptions) {
      console.log("changevalue", typeof value, value);
      this.text = value;
      // this.text = selectedOptions.map(o => o.label);
      if (selectedOptions.length == 1) {
      } else if (selectedOptions.length == 2) {
      } else if (selectedOptions.length == 3) {
        this.city = {
          label: selectedOptions[1].label,
          value: selectedOptions[1].value,
        };
        this.province = {
          label: selectedOptions[0].label,
          value: selectedOptions[0].value,
        };
        this.district = {
          label: selectedOptions[2].label,
          value: selectedOptions[2].value,
        };
      } else {
        console.log(selectedOptions);
      }
      console.log("this.text", this.text);
      // this.province = this.text[0];
      // this.city = this.text[1];
      // this.district = this.text[2];
    },
    handleVocationChange(value) {
      console.log(value); // { key: "lucy", label: "Lucy (101)" }
      this.vocation = {
        value: value.key,
        label: value.label,
      };
      console.log(this.vocation);
      // if(value == 'other'){
      //   this.isother = true;
      // }
      // else{
      //   this.isother = false;
      // }
    },
    handleSubmit(e) {
      e.preventDefault();

      this.form.validateFields((err, values) => {
        console.log("form-values", values);
        if (!err) {
          //判断是否成年
          // if (values.idNo) {
          //   this.AdultorNot(values.idNo);
          // }
          if (this.fileList.length == 0) {
            this.$message.error("请上传身份证正面照片");
            return false;
          }
          if (this.fileList2.length == 0) {
            this.$message.error("请上传身份证反面照片");
            return false;
          }
          this.loading = true;
          this.sex = values.sex;
          // this.vocation = values.vocation;
          this.address = values.realAddress;
          this.email = values.email;
          this.name = values.name;
          this.idNo = values.idNo;

          const data = {
            memberNo: this.memberNo,
            sex: this.sex,
            vocationItem: this.vocation,
            provinceItem: this.province,
            cityItem: this.city,
            districtItem: this.district,
            address: this.address,
            email: this.email,
            id: this.id,
            personIdentity: {
              identityName: this.name,
              identityNo: this.idNo,
              expiryDate: this.expiryDate,
              imgHead: this.imgHead,
              imgEmblem: this.imgEmblem,
              id: this.personid,
            },
          };
          api.setPersonData(
            data,
            (res) => {
              console.log("res", res);
              if (res.code == "OK") {
                //this.loading = false;
                // this.$message.warning("获取成功");
                if (this.$route.query.modify) {
                  this.$router.push("/userindex");
                } else {
                  this.$router.push({
                    path: "/PersonRegister/step5",
                    query: { issuc: true },
                  });
                }
              } else {
                this.loading = false;
                this.$message.warning(res.message);
              }
            },
            (err) => {
              console.log(err);
              // this.$message.warning("服务器错误");
              //  this.Confirm = false;
            }
          );
        }
      });
    },

    beforeUpload(file) {
      const isJPG = file.type === "image/jpg";
      if (!isJPG) {
        // this.$message.error("You can only upload JPG file!");
      }
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        // this.$message.error("Image must smaller than 2MB!");
      }
      return isJPG && isLt2M;
    },
    handleCancel() {
      this.previewVisible = false;
    },
    handlePreview(file) {
      this.previewImage = file.url || file.thumbUrl;
      this.previewVisible = true;
    },
    handleChange({ file, fileList }) {
      let pos = file.name.lastIndexOf(".");
      let lastName = file.name.substring(pos, file.name.length);
      let supportTypes = [".jpeg", ".png", ".jpg"]; // jpeg、 png
      if (supportTypes.indexOf(lastName.toLowerCase()) <= -1) {
        this.$message.error("上传图片仅支持 jpg、 png 2种格式！");
        return;
      }
      if (file.size / (1024 * 1024) > this.imageSize) {
        this.$message.error(`上传图片大小应小于${this.imageSize}Mb`);
        return;
      }
      this.fileList = fileList;
      let obj = fileList[0];
      if (obj.response) {
        console.log(obj.response.data);
        this.imgHead = obj.response.data;
      }
      // 根据服务端返回数据筛选上传成功的文件
      let imgUrls = [];
      fileList.forEach((file) => {
        if (file.response && file.response.code === "0") {
          imgUrls.push(file.response.data.fileInfo.url);
        }
      });
    },
    handleCancel2() {
      this.previewVisible2 = false;
    },
    handlePreview2(file) {
      this.previewImage2 = file.url || file.thumbUrl;
      this.previewVisible2 = true;
    },
    handleChange2({ file, fileList }) {
      let pos = file.name.lastIndexOf(".");
      let lastName = file.name.substring(pos, file.name.length);
      let supportTypes = [".jpeg", ".png", ".jpg"]; // jpeg、 png
      if (supportTypes.indexOf(lastName.toLowerCase()) <= -1) {
        this.$message.error("上传图片仅支持 jpeg、 png 2种格式！");
        return;
      }
      if (file.size / (1024 * 1024) > this.imageSize) {
        this.$message.error(`上传图片大小应小于${this.imageSize}Mb`);
        return;
      }
      console.log(fileList);
      // console.log(fileList.response.data)
      if (fileList.length !== 0) {
        console.log(fileList[0]);
      }
      // console.log(fileList[0].response.data)
      this.fileList2 = fileList;
      let obj = fileList[0];
      if (obj.response) {
        console.log(obj.response.data);
        this.imgEmblem = obj.response.data;

        // var xmlhttp;
        // if (window.XMLHttpRequest)
        // {
        // 	// IE7+, Firefox, Chrome, Opera, Safari 浏览器执行代码
        // 	xmlhttp=new XMLHttpRequest();
        // }
        // else
        // {
        // 	// IE6, IE5 浏览器执行代码
        // 	xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
        // }
        // xmlhttp.onreadystatechange=function()
        // {
        // 	if (xmlhttp.readyState==4 && xmlhttp.status==200)
        // 	{
        // 		console.log("12324235")
        // 	}
        // }
        // xmlhttp.open("GET","/file/file/download/"+ this.imgEmblem,true);
        // xmlhttp.send();

        // this.$axios({
        //   method:'get',
        //   url:'/file/file/download/' + this.imgEmblem,
        //   responseType:'arraybuffer',
        // })
        // .then( (res)=>{
        //   console.log('111111111111111111111111');
        //   let blob = new Blob([res.data],{type: 'image/jpeg'});
        //   let objectUrl = URL.createObjectURL(blob);
        //   window.location.href = objectUrl;
        // })

        // this.$axios.get("/file/file/download/" + this.imgEmblem).then(res => {
        //   console.log("res", res);
        // });
      }

      // 根据服务端返回数据筛选上传成功的文件
      let imgUrls = [];
      fileList.forEach((file) => {
        if (file.response && file.response.code === "0") {
          imgUrls.push(file.response.data.fileInfo.url);
        }
      });
    },
    AdultorNot(value, callback) {
      let idNoY = value.substring(6, 10);
      let idNoM = value.substring(10, 12);
      let idNoD = value.substring(12, 14);
      let current = new Date();
      let currentY = current.getFullYear();
      let currentM = current.getMonth() + 1;
      let currentD = current.getDate();
      if (currentY - idNoY < 18) {
        // this.$message.warning('未满18周岁不予以开户！');
        callback("未满18周岁不予以开户！");
        return false;
      } else if (currentY - idNoY == 18) {
        if (currentM - idNoM < 0) {
          // this.$message.warning('未满18周岁不予以开户！');
          callback("未满18周岁不予以开户！");
          return false;
        } else if (currentM - idNoM == 0) {
          if (currentD - idNoD <= 0) {
            // this.$message.warning('未满18周岁不予以开户！');
            callback("未满18周岁不予以开户！");
            return false;
          } else {
          }
        } else {
        }
      } else {
      }
    },
  },
};
</script>
<style scoped>
.formGroupTitle {
  font-size: 20px;
  font-weight: bold;
  text-align: right;
}

.avatar-uploader {
  float: left;
}

.avatar-uploader > .ant-upload {
  width: 128px;
  height: 128px;
}

.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}

.btn-class {
  border: 1px solid #ccc;
  background: #ccc;
  color: #333;
}

.width-sty {
  width: 60%;
}

.submitButton {
  width: 8vw;
}
</style>